﻿using System;
using System.Linq;
using System.Web.Mvc;
using FinancePortal.Business.Infraestructure;
using FinancePortal.Business.Repository;
using FinancePortal.Domain.Enum;
using FinancePortal.Web.Model;
using FinancePortal.Web.Models;

namespace FinancePortal.Web.Controllers
{
    [Permission(Roles = "Worker, Administrator")]
    public class ResourceController : Controller
    {
        private readonly IResourceRepository _resourceRepository;
        private readonly IAreaRepository _areaRepository;

        public ResourceController(IResourceRepository resourceRepository, IAreaRepository areaRepository)
        {
            _resourceRepository = resourceRepository;
            _areaRepository = areaRepository;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ResourceList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                //var ids = ResourceManagement.GetAreas(HttpContext);
                //var idArea = _resourceRepository.GetBySOEID(ResourceManagement.GetSOEID(this.Request)).AreaId;

                var resources = _resourceRepository.GetAll()//GetByArea(idArea)
                    .Where(r => r.Profile != (int)Profile.Client)
                    .OrderBy(jtSorting)
                    .Skip(jtStartIndex)
                    .Take(jtPageSize)
                    .ToList();

                var resourcesList = resources.Select(m =>
                    new ResourceViewModel
                    {
                        Id = m.Id,
                        Name = m.Name,
                        SOEID = m.SOEID,
                        Email = m.Email,
                        Profile = m.Profile,
                        AreaId = m.AreaId
                    }).ToList();

                return Json(new
                {
                    Result = "OK",
                    Records = resourcesList,
                    TotalRecordCount = _resourceRepository.GetAll().Where(r => r.Profile != (int)Profile.Client).Count()
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult GetProfile()
        {
            var profiles = (from Profile e in System.Enum.GetValues(typeof(Profile))
                            select new { Value = e, DisplayText = e.ToString() }).ToList();

            return Json(new
            {
                Result = "OK",
                Options = profiles
            });
        }

        [HttpPost]
        public JsonResult GetArea()
        {
            try
            {
                //var ids = ResourceManagement.GetAreas(HttpContext);
                //var idArea = _resourceRepository.GetBySOEID(ResourceManagement.GetSOEID(this.Request)).AreaId;
                var areas = _areaRepository.GetAll().Where(a => a.AreaClient == false) //GetByResource(idArea)
                    .Select(m =>
                    new
                    {
                        Value = m.Id,
                        DisplayText = m.Name
                    }).ToList();

                return Json(new
                {
                    Result = "OK",
                    Options = areas
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles = "Administrator")]
        public JsonResult CreateResource(ResourceViewModel view)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! Please correct it and try again."
                    });
                }

                //_resourceRepository.Save(ResourceViewModel.ToModel(view));

                var model = ResourceViewModel.ToModel(view);
                _resourceRepository.Save(model);
                view.Id = model.Id;

                return Json(new
                {
                    Result = "OK",
                    Record = view
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles = "Administrator")]
        public JsonResult UpdateResource(ResourceViewModel view)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! Please correct it and try again."
                    });
                }

                _resourceRepository.Save(ResourceViewModel.ToModel(view));

                return Json(new
                {
                    Result = "OK"
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        [Transactional]
        [Permission(Roles = "Administrator")]
        public JsonResult DeleteResource(int id)
        {
            try
            {
                var model = _resourceRepository.GetById(id);
                _resourceRepository.Delete(model);

                return Json(new
                {
                    Result = "OK"
                });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        #region Old Actions
        /*
        public ActionResult Index()
        {
            var ids = ResourceManagement.GetAreas(HttpContext);
            var list = _resourceRepository.GetByArea(ids);

            return View(list);
        }

        [Permission(Roles = "Administrator")]
        public ActionResult Create()
        {
            LoadDropDown();

            return View();
        }

        [HttpPost, Transactional, Permission(Roles = "Administrator")]
        public ActionResult Create(Resource resource)
        {
            if (ModelState.IsValid)
            {
                _resourceRepository.Save(resource);
                return RedirectToAction("Index");
            }

            LoadDropDown();

            return View(resource);
        }

        private void LoadDropDown()
        {
            var ids = ResourceManagement.GetAreas(HttpContext);
            var listArea = _areaRepository.GetByResource(ids);

            ViewBag.Area = new SelectList(listArea, "Id", "Name");
            ViewBag.Profile = Profile.Administrator.ToSelectList(); ;
        }

        [Permission(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            var resource = _resourceRepository.GetById(id);

            LoadDropDown();

            return View(resource);
        }

        [HttpPost, Transactional, Permission(Roles = "Administrator")]
        public ActionResult Edit(Resource resource)
        {
            if (ModelState.IsValid)
            {
                _resourceRepository.Save(resource);
                return RedirectToAction("Index");
            }

            LoadDropDown();

            return View(resource);
        }

        [Transactional, Permission(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            var resource = _resourceRepository.GetById(id);
            _resourceRepository.Delete(resource);

            return RedirectToAction("Index");
        }*/

        #endregion
    }
}
